import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router'
import {login,getUserInfo} from "@/api/common.js"
import {
	Message
} from 'element-ui';
import _cache from '@/utils/cache'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		isLogin: false, //是否登录
		user_info: {},
	},
	mutations: {
		//设置登陆状态
		setLoginStatus(state, status = true) {
			state.isLogin = status
		},
		//设置用户信息
		setUserInfo(state, info = {}) {
			state.user_info = info
		},
	},
	actions: {
		async vuex_login(context,params={}) {
			let res = await login(params)
			if(res.code != 200){
				Message({
					type: 'error',
					message: res.message,
					duration: 1500
				})
				return false;
			}
			Message({
				type: 'success',
				message: '登陆成功',
				duration: 1500
			})
			window.localStorage.setItem('token', res.data.token)
			setTimeout(function(){
				window.location.reload();
			},1500)
		},
		//退出
		vuex_out(context){
			//退出登陆
			Message({
				type: 'success',
				message: '退出成功',
				duration: 1500
			})
			
			_cache.remove('token')
			context.commit('setLoginStatus', false)
			context.commit('setUserInfo')
			window.location.reload();
		},
		async vuex_get_user_info(context){
			let res = await getUserInfo()
			if(res.code == 201){
				Message({
					type: 'error',
					message: '用户登录过期请重新登录',
					duration: 1500
				})
				_cache.clearAll()
				context.commit('setLoginStatus', false)
				router.replace({
					path:'/'
				})
				return false;
			}
			if(res.code == 200){
				context.commit('setLoginStatus', true)
				context.commit('setUserInfo', res.data)
				return false
			}
			Message({
				type: 'error',
				message: res.message,
				duration: 1500
			})
			
		}

	},
	modules: {}
})